import React from 'react';
import style from './style';
import { IconFont } from '../../ui-components';
import cx from 'classnames'
import util from '../../util'

class PeriodsSelect extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'PeriodsSelect';
    this.state = {
      isClose: true,
    }
  }
  handleFocus = () => {
    this.setState({
      isClose: false,
    });
  }
  handleBlur = () => {
    this.setState({
      isClose: true,
    });
  }
  emitFocus = () => {
    this.refs.input.focus();
  }
  handleClick = () => {
    this.emitFocus();
  }
  onChange = (v) => {
    this.props.onChange && this.props.onChange(v)
    this.refs.input.blur();
  }
  render() {
    const {
      list,
      value,
    } = this.props;
    const {
      isClose, 
    } = this.state;
    let styles = {};
    if(isClose) {
      styles = {
        height: '22px',
      }
    }else {
      styles = {
        height: `${list.length > 5 ? 6 * 22 : (list.length + 1) * 22}px`,
      }
    }
    return (
      <div className={style['select-box']} style={styles}>
        <div className={style['select-value']} onMouseDown={util.preventDefaultEvent} onClick={this.handleClick}>
          <span>{value.name}</span>
          <IconFont value='arrow' className={style['arrow']}/>
        </div>
        <input 
          className={style['select-input']}
          ref={'input'}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
        />
        <div className={style['select-list']} style={{
          height: `${list.length > 5 ? 5 * 22 : list.length * 22}px`,
          overflowY: 'scroll',
        }}>
          {
            list.map( (v, i) => {
              return (
                <div key={i} onMouseDown={util.preventDefaultEvent} onClick={this.onChange.bind(this, v)} className={cx({
                  [style['select-value']]: true,
                  [style['select-item']]: true,
                  [style['select-active']]: value.objectivePeriodId === v.objectivePeriodId,
                })}>
                  <span>{v.name}</span>
                </div>
              );
            })
          }
          
        </div>
      </div>
    );
  }
}

export default PeriodsSelect;
